package com.atguigu.crowd.mvc.config;

import com.atguigu.crowd.constant.CrowdConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;

// 注意！这个类一定要放在自动扫描的包下，否则所有配置都不会生效！
//spring-security配置类
// 将当前类标记为配置类
@Configuration
@Component
// 启用Web环境下权限控制功能
@EnableWebSecurity
//启用全局方法权限控制 并且设置prePostEnabled=true
// 保证@PreAuthority、 @PostAuthority、@PreFilter、@PostFilter 生效
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {



     @Autowired  //将数据库查询要用到的类装配进来
      private UserDetailsService userDetailsService;


    //每次调用此方法中会检查是否有BCryptPasswordEncoder bean
    //默认为单例
//    @Bean  //将BCryptPasswordEncoder放入IOC容器
//    public BCryptPasswordEncoder getPasswordEncoder() {
//        return new BCryptPasswordEncoder();
//    }

    @Autowired
    private BCryptPasswordEncoder passwordEncoder; //spring security提供的带盐值的加密

    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security
                .authorizeRequests()
                .antMatchers("/admin/to/login/page.html")
                .permitAll()
//                .antMatchers("/security/do/login.html")
//                .permitAll()
                .antMatchers("/bootstrap/**")
                .permitAll()
                .antMatchers("/css/**")
                .permitAll()
                .antMatchers("/fonts/**")
                .permitAll()
                .antMatchers("/img/**")
                .permitAll()
                .antMatchers("/jquery/**")
                .permitAll()
                .antMatchers("/layer/**")
                .permitAll()
                .antMatchers("/script/**")
                .permitAll()
                .antMatchers("/ztree/**")
                .permitAll()
               // .antMatchers("/admin/get/page.html")              //用户维护页 针对分页显示 Admin 数据设定访问控制
               // .hasRole("经理")
             //   .access("hasRole('经理')OR hasAuthority('user:get')")// 要 求 具 备 “ 经 理 ” 角 色 和 “user:get”权限二者之一
                .anyRequest()
                .authenticated()
                .and()
                .exceptionHandling()            //异常处理
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                        //放进request域中 在system-error.jsp就可以拿到异常消息
                        httpServletRequest.setAttribute("exception", new Exception(CrowdConstant.MESSAGE_ACCESS_DENIED));
                        httpServletRequest.getRequestDispatcher("/WEB-INF/system-error.jsp").forward(httpServletRequest,httpServletResponse);
                    }
                })
                .and()
//                .csrf()
//                .disable()
                .formLogin()
                .loginPage("/admin/to/login/page.html") //登录页面
                .loginProcessingUrl("/security/do/login.html")  //处理登录
                .permitAll()
                .defaultSuccessUrl("/admin/to/main/page.html") //登录成功后跳转到后台主页面
                .usernameParameter("loginAcct")          //账号请求参数名称
                .passwordParameter("userPswd")
                .and()
                .logout()
                .logoutUrl("/security/do/logout.html")
                .logoutSuccessUrl("/admin/to/login/page.html")
        ;
    }


        @Override
        protected void configure(AuthenticationManagerBuilder builder) throws Exception {
           //使用基于数据库的认证
            builder.userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder);

    }

}
